package com.web.music.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

import com.web.music.interfaces.PersistenceHelper;
import com.web.music.model.PersistentObject;
import com.web.music.model.PersistentObjectRegistry;
import com.web.music.model.Track;

@Transactional
public class PersistenceHelperImpl implements PersistenceHelper {

	private EntityManager em;

	@PersistenceContext
	public void setEntityManager(EntityManager em) {
		this.em = em;
	}

	public EntityManager getEntityManager() {
		return em;
	}
	
	public void save(PersistentObject object) {
		if (object.getId() == null) {
			getEntityManager().persist(object);
		} else {
			getEntityManager().merge(object);
		}
	}
	
	public void saveAll(List<? extends PersistentObject> objects) {
		for (PersistentObject object: objects){
			save(object);
		}
	}

	public PersistentObject getById(Class<? extends PersistentObject> clazz, Long id) {
		return getEntityManager().find(clazz, id);
	}
	
	@SuppressWarnings("unchecked")
	public List<PersistentObject> findAll(Class<? extends PersistentObject> clazz) {
		String entity = clazz.getSimpleName();
		return getEntityManager().createQuery("select e FROM " + entity + " e").getResultList();
	}

	public void delete(PersistentObject object) {
		getEntityManager().remove(object);
	}
	
	public void deleteEverything(){
		List<Class<? extends PersistentObject>> classes = PersistentObjectRegistry.getClasses();
		for (Class<? extends PersistentObject> clazz: classes){
			List<PersistentObject> objects = findAll(clazz);
			for (PersistentObject o: objects){
				delete(o);
			}
		}
	}
	
	//TO-DO write 3 methods :)
	 @SuppressWarnings("unchecked")
	public List<Track> findTracksByName(String s){
		 try{
			List<Track> resultList = getEntityManager().createNamedQuery("findTracksByName").setParameter("trackName", s).getResultList();
			 return resultList;		
		 }catch(NullPointerException e){
			 System.err.println("NullPointerException ;(");
		 }
		 //.setParameter("trackName", ""+s+"");
		 return null;	
		
	 };
	 public List<Track> findTracksByArtistId(long id){
		 try{
				List<Track> resultList = getEntityManager().createNamedQuery("findTracksByArtistId").setParameter("Artist_id)", id).getResultList();
				 return resultList;		
			 }catch(NullPointerException e){
				 System.err.println("NullPointerException ;(");
			 }
		 return null;
	 };
	 
	 public List<Track> findTracksByPersonId(long id){
		 return null;
	 };

}
